/* eslint-disable max-len */
import { SetupContext, computed, defineComponent, onMounted, provide, ref, watch } from 'vue';
import { designerCanvasProps, DesignerCanvasPropsType } from './composition/props/designer-canvas.props';
import { useDragula } from './composition/function/use-dragula';
import { UseDragula } from './composition/types';
import { DesignerItemContext } from './types';
import FDesignerItem from './components/designer-item.component';
import './composition/class/designer-canvas.css';
import './composition/class/control.css';
import { cavasChanged, setPositionOfBtnGroup } from './composition/designer-cavas-changed';

export default defineComponent({
    name: 'FDesignerCanvas',
    props: designerCanvasProps,
    emits: ['init', 'selectionChange'],
    setup(props: DesignerCanvasPropsType, context: SetupContext) {
        const schema = ref();
        const designerCanvasElementRef = ref();
        const designerItemElementRef = ref();
        const componentInstance = ref();
        const useDragulaComposition = useDragula();

        provide<UseDragula>('canvas-dragula', useDragulaComposition);
        provide<DesignerItemContext>('design-item-context', {
            designerItemElementRef,
            componentInstance,
            schema: schema.value,
            parent: undefined
        });

        const designerCanvasClass = computed(() => {
            const classObject = {
                'd-flex': true,
                'flex-fill': true,
                'flex-column': true
            } as Record<string, boolean>;
            return classObject;
        });

        onMounted(() => {
            if (designerCanvasElementRef.value) {
                useDragulaComposition.initializeDragula(designerCanvasElementRef.value);
            }
            schema.value = props.modelValue;
            context.emit('init', useDragulaComposition);
        });

        watch(
            cavasChanged,
            (newInfo: any) => {
                console.log(newInfo);
                setPositionOfBtnGroup(designerCanvasElementRef.value);
            },
            {
                flush: 'post'
            }
        );

        function onSelectionChange(schemaType: string) {
            context.emit('selectionChange', schemaType);
        }

        return () => {
            return (
                <div class="editorDiv flex-fill h-100">
                    <div class="editorPanel d-flex flex-fill flex-column PC f-area-response f-area-response--sm f-area-response--md f-area-response--lg">
                        <div ref={designerCanvasElementRef} class={designerCanvasClass.value}>
                            {schema.value && <FDesignerItem v-model={schema.value} onSelectionChange={(payload: string) => onSelectionChange(payload)}></FDesignerItem>}
                        </div>
                    </div>
                </div>
            );
        };
    }
});
